package logic

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func Proto2Pb(protoFilePath string) {
	fmt.Printf("Converting %s to pb...\n", protoFilePath)

	// Check if 'protoc' is installed
	_, err := exec.LookPath("protoc")
	if err != nil {
		fmt.Println("protoc is not installed. Please install protoc first.")
		return
	}

	// Get current directory
	currentDir, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get current directory: %v", err)
	}
	fmt.Printf("Current directory: %s\n", currentDir)

	// Get the base name of the proto file (without path or extension)
	baseName := strings.TrimSuffix(filepath.Base(protoFilePath), filepath.Ext(protoFilePath))

	// Build protoc command
	protocCmd := exec.Command("protoc",
		fmt.Sprintf("--go_out=%s", currentDir),
		fmt.Sprintf("--go-grpc_out=%s", currentDir),
		protoFilePath,
	)

	// Execute the protoc command
	var out []byte
	out, err = protocCmd.CombinedOutput()
	if err != nil {
		log.Fatalf("protoc failed: %v\n%s", err, out)
	}

	// Output success information
	fmt.Printf("protoc executed successfully. Output:\n%s\n", out)

	// Check if the generated file exists
	goFilePath := filepath.Join(currentDir, baseName+".pb.go")
	grpcFilePath := filepath.Join(currentDir, baseName+"_grpc.pb.go")

	// Check if the generated files exist
	if _, err := os.Stat(goFilePath); os.IsNotExist(err) {
		log.Fatalf("Generated .pb.go file does not exist: %s", goFilePath)
	}
	if _, err := os.Stat(grpcFilePath); os.IsNotExist(err) {
		log.Fatalf("Generated .grpc.pb.go file does not exist: %s", grpcFilePath)
	}

	fmt.Printf("Generated pb files: %s and %s\n", goFilePath, grpcFilePath)
}
